package com.my.code.priorityqueue;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;

public class PrioritizedTask implements Runnable, Comparable<PrioritizedTask> {
    private Random rand = new Random(47);
    private static int counter = 0;
    private final int id = counter++;
    private final int priority;
    protected static List<PrioritizedTask> sequence = new ArrayList<>();

    public PrioritizedTask(int priority) {
        this.priority = priority;
        sequence.add(this);
    }

    @Override
    public int compareTo(PrioritizedTask o) {
        return Integer.compare(priority, o.priority);
    }

    @Override
    public void run() {
        try {
            TimeUnit.MILLISECONDS.sleep(250);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("done " + this);
    }

    @Override
    public String toString() {
        return String.format("[%1$-3d]", priority) + " Task id = " + id;
    }

    public String summary() {
        return "PT(id=" + id + ":" + priority + ")";
    }

    //终止任务线程和统计
    public static class EndSentinel extends PrioritizedTask {
        private ExecutorService exec;

        public EndSentinel(ExecutorService e) {
            super(8);//根据比较器，数值越小，优先级越高
            this.exec = e;
        }

        @Override
        public void run() {
            int count = 0;
            for (PrioritizedTask pt : sequence) {//结束之前打印队列中所有的情况
                System.out.print(pt.summary() + " ");
                if (++count % 10 == 0) System.out.println();
            }
            System.out.println();
            System.out.println(this + " calling shutdownNow");
            exec.shutdownNow();
        }
    }
}
